package com.csthink.mr.wordcount;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * @author <a href="mailto:csthink@icloud.com">Mars</a>
 * @since 2024-04-12 16:52
 */
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

    public static final IntWritable ONE = new IntWritable(1);

    @Override
    protected void setup(Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        System.out.println("WordCountMapper-setup");
    }

    /**
     * @param k1      每行数据的偏移量，不是行号
     * @param v1      每行的数据内容
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void map(LongWritable k1, Text v1, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        String[] words = v1.toString().split(",");
        for (String word : words) {
            context.write(new Text(word), ONE);
        }
    }

    @Override
    protected void cleanup(Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        System.out.println("WordCountMapper-cleanup");
    }
}
